<template>
  <!-- 表单组件，用于添加分类 -->
  <el-form :model="formData" label-width="auto" style="max-width: 600px" ref="form1Ref" :rules="rules">
    <!-- 名称输入框 -->
    <el-form-item label="名称" prop="name">
      <el-input v-model="formData.name" />
    </el-form-item>
    <!-- 图片上传组件 -->
    <el-form-item label="图片" prop="img">
      <Tuku v-model="formData.img" />
    </el-form-item>
    <!-- 父类选择器 -->
    <el-form-item label="父类">
      <CategoryTree v-model="formData.parentId" ref="categoryTreeRef"></CategoryTree>
    </el-form-item>
    <!-- 状态选择器 -->
    <el-form-item label="状态">
      <Enum v-model="formData.status" enumName="CategoryStatus"></Enum>
    </el-form-item>
    <!-- 排序输入框 -->
    <el-form-item label="排序">
      <el-input-number :min="0" v-model="formData.seq" />
    </el-form-item>
    <!-- 提交和重置按钮 -->
    <el-form-item>
      <el-button type="primary" @click="submit()">提交</el-button>
      <el-button @click="resetForm()">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
// 导入组件和依赖
import Tuku from '@/components/Tuku.vue';
import Enum from '@/components/Enum.vue';
import { onMounted, reactive, ref } from 'vue';
import categoryApi from '@/api/categoryApi';
import { ElMessage } from 'element-plus';
import CategoryTree from '@/components/CategoryTree.vue';

// 定义引用
const categoryTreeRef = ref();
const form1Ref = ref();

// 定义表单数据
const formData = reactive({
  name: '',
  img: '',
  status: 0,
  parentId: 0,
  seq: 1
});

/**
 * 提交表单
 * 将表单数据发送到后端API进行添加操作，并在成功后显示提示信息
 * 同时刷新父类选择器的数据
 */
const submit = () => {
  categoryApi.add.call(formData).then(() => {
    ElMessage.success("添加成功");
    categoryTreeRef.value.callCategoryApi();
  });
}

// 组件挂载完成后执行的钩子函数
onMounted(() => {
  // 可以在这里进行初始化操作
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ]
}

/**
 * 重置表单
 * 清空表单数据，恢复初始状态
 */
const resetForm = () => {
  // 清空表单数据
}
</script>